//
//  MTCProjectDetailViewController.m
//  ERP
//
//  Created by QA on 15/9/25.
//  Copyright (c) 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MTCProjectDetailViewController.h"

#import "NSDictionary+DataFormat.h"
#import "NSMutableDictionary+Format.h"
#import "WebServiceCommonRequest.h"

#import "AutoTextTableViewCell.h"
#import "MTCContractShipmentViewCell.h"

#import "MTCCreateProjectViewController.h"
#import "MTCContractRWDDetailViewController.h"
#import "MTCContractRWDListViewController.h"

@interface MTCProjectDetailViewController ()

@property (nonatomic,strong) NSDictionary *projectModelInfo;
@property (strong, nonatomic) NSDictionary *concreteInfo;

@property (nonatomic,strong) NSArray *resultData;
@property (nonatomic,assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@property (nonatomic,strong) NSMutableArray *projectArray;

@end

@implementation MTCProjectDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle:@"合同工程明细"];
        NSArray *mainMenuArray1 = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_HTGC_CZ"];
        if (mainMenuArray1.count>0){
            UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(createClienterSelector:)];
            self.navigationItem.rightBarButtonItem = leftButton;
        }
    }
    return self;
}

- (void)getPassingParameter:(id)object
{
    if (!object) return;
    NSArray *array = object;
    self.concreteInfo = [array firstObject];
    self.projectModelInfo = [array lastObject];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.orderContentState = 0;
    [self setShowValueView:self.projectModelInfo];
    
    //获取所有合同
    [self getClienterContractOrderInfo];
}

- (void)setShowValueView:(NSDictionary*)dic
{
    self.projectArray = [NSMutableArray array];
    [self addContractInfoKey:@"工程名称" toKey:@"工程名称：" defaults:@"未知" format:nil form:dic toArray:_projectArray];
    [self addContractInfoKey:@"建设单位" toKey:@"建设单位：" defaults:@"未知" format:nil form:dic toArray:_projectArray];
    [self addContractInfoKey:@"施工单位" toKey:@"施工单位：" defaults:@"未知" format:nil form:dic toArray:_projectArray];
    [self addContractInfoKey:@"运输距离" toKey:@"工地距离：" defaults:@"未知" format:@"%@公里" form:dic toArray:_projectArray];
    [self addContractInfoKey:@"工地地址" toKey:@"工地地址：" defaults:@"未知" format:nil form:dic toArray:_projectArray];
    [self addContractInfoKey:@"工地联系人" toKey:@"工地联系人：" defaults:@"未知" format:nil form:dic toArray:_projectArray];
    [self addContractInfoKey:@"工地联系电话" toKey:@"工地联系电话：" defaults:@"未知" format:nil form:dic toArray:_projectArray];
    [self addContractInfoKey:@"备注" toKey:@"备      注：" defaults:@"无" format:nil form:dic toArray:_projectArray];
    
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}


#pragma mark - 网络客户合同信息
- (void)getClienterContractOrderInfo
{
    //判断是否需要获取任务单
    if(!self.projectModelInfo) return;
    NSString *projectID = [self.projectModelInfo objectFormatStringForKey:@"工程ID"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_RWD_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"起始条数" value:[NSNumber numberWithInteger:1]];
    [content addParameterKey:@"结束条数" value:[NSNumber numberWithInteger:5]];
    [content addParameterKey:@"合同ID" value:nil defaults:@"0"];
    [content addParameterKey:@"订单ID" value:nil defaults:@"0"];
    [content addParameterKey:@"工程ID" value:projectID defaults:@"0"];
    [content addParameterKey:@"状态" value:@""];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            self.resultData = firstArray;
            self.orderContentState = 3;
        } else {
            self.orderContentState = 1;
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
    }];
    
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 1) {
        NSInteger count = self.resultData.count;
        return count > 0 ? count + 1 : 1;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //合同结算信息
    if (indexPath.section == 0 && indexPath.row == 0){
        NSString *identifier = [NSString stringWithFormat:@"MTCClienterDetailOne%ld",(long)indexPath.section];
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        [cell setDataArray:self.projectArray];
        return cell;
        
    } else if (indexPath.section == 1){
        if (self.orderContentState == 3) {
            
            //添加，显示全部按钮
            if (indexPath.row >= self.resultData.count) {
                static NSString *CellIdentifier = @"MTCContractShipmentViewCellButton";
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (!cell) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                cell.textLabel.text = @"查看全部任务单>>>";
                cell.textLabel.textAlignment = NSTextAlignmentCenter;
                cell.textLabel.textColor = ThemeColorOrange;
                cell.backgroundColor = [UIColor whiteColor];
                return cell;
            }
            
            static NSString *CellIdentifierOne = @"MTCContractShipmentViewCell";
            MTCContractShipmentViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
            if (!cell) cell = [[MTCContractShipmentViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
            
            //添加分割线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 81.5, SuperWidth, 0.5)];
            lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
            [cell.contentView addSubview:lineView];
            
            //任务单信息设置
            NSDictionary *itemData = [self.resultData objectAtIndex:indexPath.row];
            cell.rwdbhLabel.text = [itemData objectFormatStringForKey:@"任务单编号" defaults:@"未知"];
            cell.gcmcLabel.text = [itemData objectFormatStringForKey:@"工程名称" defaults:@"未知"];
            cell.sgbwLabel.text = [itemData objectFormatStringForKey:@"施工部位" defaults:@"未知"];
            cell.jhkpLabel.text = [itemData objectFormatStringForKey:@"工地计划开盘时间" defaults:@"未知"];
            cell.ztLabel.text = [itemData objectFormatStringForKey:@"状态" defaults:@"未知"];
            cell.jhflLabel.text = [itemData objectFormatStringForKey:@"计划方量" format:@"计划%@方" defaults:@"未知"];
            cell.qddjLabel.text = [itemData objectFormatStringForKey:@"砼强度" defaults:@"未知等级"];
            cell.jzfsLabel.text = [itemData objectFormatStringForKey:@"浇筑方式" defaults:@"非泵送"];
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MTCClienterDetailHT"];
            cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
            
            if(self.orderContentState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 30.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"未找到任务单";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载任务单失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, SuperWidth - 10, 29.5)];
    lable.textColor = ThemeColorBlue;
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if(section == 0){
        lable.text = @"工程基本信息";
    } else if(section == 1){
        lable.text = @"工程近5单任务单";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.projectArray];
        return cell.contentView.frame.size.height;
    }
    
    if (indexPath.row >= self.resultData.count) return 56;
    else if (self.resultData.count > 0) return 82;
    else return 56;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        if(self.orderContentState == 2) {//加载失败执行
            self.orderContentState = 0;
            [self.tableView reloadData];
            [self getClienterContractOrderInfo];
            
        } else if(self.orderContentState == 3) { //加载成功
            if (indexPath.row >= self.resultData.count){
                //查看所有任务单
                NSString *projectID = [self.projectModelInfo objectFormatStringForKey:@"ID"];
                MTCContractRWDListViewController *viewController = [[MTCContractRWDListViewController alloc] initWithProjectID:projectID];
                [self.navigationController pushViewController:viewController animated:YES];
            } else {
                //产看任务单明细
                NSDictionary *itemData = [self.resultData objectAtIndex:indexPath.row];
                MTCContractRWDDetailViewController *viewController = [[MTCContractRWDDetailViewController alloc] initWithValue:itemData];
                [self.navigationController pushViewController:viewController animated:YES];
            }
        }
    }
}

#pragma mark -
#pragma mark Button Selector

- (void)createClienterSelector:(id)sender
{
    NSArray *valueArray = @[self.concreteInfo,self.projectModelInfo];
    
    MTCCreateProjectViewController *viewController = [[MTCCreateProjectViewController alloc] initWithValue:valueArray];
    viewController.backResultDelagate = self;
    [self.navigationController pushViewController:viewController animated:YES];
}


- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    if (!backValue) return;
    [self setShowValueView:backValue];
    
    //更新列表页面
    if (self.backResultDelagate) {
        NSArray *backResult = @[self.projectModelInfo,backValue];
        [self.backResultDelagate backResultDataKey:self.key dataValue:backResult];
        self.projectModelInfo = backValue;
    }
}

@end